package com.voicechat.firstmet;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.av.sdk.AVContext;
import com.tencent.ilivesdk.ILiveSDK;
import com.voicechat.firstmet.activity.VoiceCommActivity;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.fragment.CommunityFragment;
import com.voicechat.firstmet.fragment.MeFragment;
import com.voicechat.firstmet.fragment.NearbyFragment;
import com.voicechat.firstmet.fragment.VoiceChatFragment;
import com.voicechat.firstmet.imcontrol.Conversation;
import com.voicechat.firstmet.imcontrol.ConversationPresenter;
import com.voicechat.firstmet.imcontrol.ConversationView;
import com.voicechat.firstmet.imcontrol.MessageFactory;
import com.voicechat.firstmet.imcontrol.NomalConversation;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.LocationService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.realm.GiftDataBean;
import com.voicechat.firstmet.realm.ListBean;
import com.voicechat.firstmet.service.DownloadService;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.ContDownUtil;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.RealmUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.SystemBarTintManager;
import com.voicechat.firstmet.utils.ThreadManager;
import com.voicechat.firstmet.utils.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.RealmResults;

public class MainActivity extends BaseActivity implements View.OnClickListener,ConversationView {
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R.id.main_comm_iv)
    ImageView mainCommIv;
    @BindView(R.id.main_comm_tv)
    TextView mainCommTv;
    @BindView(R.id.main_vv_ll)
    LinearLayout mainVvLl;
    @BindView(R.id.main_voice_chat_iv)
    ImageView mainVoiceChatIv;
    @BindView(R.id.main_voice_chat_tv)
    TextView mainVoiceChatTv;
    @BindView(R.id.main_voice_chat_ll)
    LinearLayout mainVoiceChatLl;
    @BindView(R.id.voice)
    ImageView voice;
    @BindView(R.id.main_voice_ll)
    LinearLayout mainVoiceLl;
    @BindView(R.id.main_nearby_iv)
    ImageView mainNearbyIv;
    @BindView(R.id.main_nearby_tv)
    TextView mainNearbyTv;
    @BindView(R.id.main_nearby_ll)
    LinearLayout mainNearbyLl;
    @BindView(R.id.main_me_iv)
    ImageView mainMeIv;
    @BindView(R.id.main_me_tv)
    TextView mainMeTv;
    @BindView(R.id.main_me_ll)
    LinearLayout mainMeLl;
    private static String TAG = "MainActivity";
    private CommunityFragment commFragment;
    private VoiceChatFragment voiceChatFragment;
    private NearbyFragment nearbyFragment;
    private MeFragment meFragment;
    private String showFragmentTag = "commFragment";
    private static final int REQUEST_CONTACTS = 1000;
    private static final String[] PERMISSIONS_CONTACT = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA,};
    private LocationService locationService;
   // public String[] stringsText = getResources().getStringArray(R.array.vip_text);
    //public String[] stringsTitle = getResources().getStringArray(R.array.vip_title);

    /**
     * 所有点击事件的id集合
     */
    private int[] ids = {R.id.main_vv_ll, R.id.main_voice_chat_ll,
            R.id.main_voice_ll,R.id.main_nearby_ll,R.id.main_me_ll};
    private SystemBarTintManager mTintManager;
    private int flag;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String deviceInfo;
    private Runnable runnable;
    private ContDownUtil contDownUtil;
    private Handler mHandler;
    private ConversationPresenter presenter;
    private boolean isShow = true;//是否拒绝

    @Override
    protected int setStatusBarColor() {
        return R.color.colorWhite;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return true;
    }
    @Override
    protected int loadLayout() {
        return R.layout.activity_main;
    }
    @Override
    protected void initLayout(Bundle savedInstanceState) {
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        ButterKnife.bind(this);
        presenter = new ConversationPresenter(this);
        presenter.getConversation();
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        flag = getIntent().getIntExtra("flag", 0);
        setTabSelection(flag);
        for (int id : ids) {
            findTById(id).setOnClickListener(this);
        }
        Log.i(TAG, "initLayout: ----------"+" iLiveSDK: "+ILiveSDK.getInstance().getVersion()+"\n IMSDK:"+
                TIMManager.getInstance().getVersion()+"\n AVSDK:"+
                AVContext.sdkVersion);
    }
    @Override
    public void onResume() {
        super.onResume();
        refresh();
        if(isShow) {
            regist();
            setHttpVersion();
        }
    }
    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            //点击社区
            case R.id.main_vv_ll:
                setTabSelection(0);
                break;
            //点击语聊
            case R.id.main_voice_chat_ll:
                setTabSelection(1);
                break;
            //点击语音通话
            case R.id.main_voice_ll:
                //setTabSelection(2);
                intent = new Intent(this, VoiceCommActivity.class);
                startActivity(intent);
                break;
            //点击附近
            case R.id.main_nearby_ll:
                setTabSelection(3);
                break;
            //点击我的
            case R.id.main_me_ll:
                setTabSelection(4);
                break;
        }
    }

    /*恢复fragment界面*/
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            String showFragmentTag = savedInstanceState.getString(SPUtils.SHOW_TAG);
            if (showFragmentTag != null) {
                Fragment showFragment = getSupportFragmentManager().findFragmentByTag(showFragmentTag);
                switch (showFragmentTag) {
                    case "CommunityFragment":
                        commFragment = (CommunityFragment) showFragment;
                        setTabSelection(0);
                        break;
                    case "VoiceChatFragment":
                        voiceChatFragment = (VoiceChatFragment) showFragment;
                        setTabSelection(1);
                        break;
                   /* case "VoiceCommFragment":
                        voiceCommFragment = (VoiceCommFragment) showFragment;
                        setTabSelection(2);
                        break;*/
                    case "NearbyFragment":
                        nearbyFragment = (NearbyFragment) showFragment;
                        setTabSelection(3);
                        break;
                    case "meFragment":
                        meFragment = (MeFragment) showFragment;
                        setTabSelection(4);
                        break;

                }
            }
        }
    }
    @Override
    protected void clearSelection() {//清空底部Tab的选中状态,当点击的时候再自定义选中Tab的状态
        super.clearSelection();
        mainCommIv.setImageResource(R.mipmap.un_comm);
        mainCommTv.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        mainVoiceChatIv.setImageResource(R.mipmap.un_chat);
        mainVoiceChatTv.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        mainNearbyIv.setImageResource(R.mipmap.un_nearby);
        mainNearbyTv.setTextColor(getResources().getColor(R.color.colorAAAAAA));
        mainMeIv.setImageResource(R.mipmap.un_me);
        mainMeTv.setTextColor(getResources().getColor(R.color.colorAAAAAA));
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
        outState.putString(SPUtils.SHOW_TAG, showFragmentTag);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {//防止反复创建，造成重叠
        super.onAttachFragment(fragment);
        if (fragment instanceof CommunityFragment) {
            commFragment = (CommunityFragment) fragment;
        }
        if (fragment instanceof VoiceChatFragment) {
            voiceChatFragment = (VoiceChatFragment) fragment;
        }
       /* if (fragment instanceof VoiceCommFragment) {
            voiceCommFragment = (VoiceCommFragment) fragment;
        }*/
        if (fragment instanceof NearbyFragment) {
            nearbyFragment = (NearbyFragment) fragment;
        }
        if (fragment instanceof MeFragment) {
            meFragment = (MeFragment) fragment;
        }
    }

    @Override
    protected void hideFragments(FragmentTransaction transaction) {
        super.hideFragments(transaction);
        if (null != commFragment) {
            transaction.hide(commFragment);
        }
        if (null != voiceChatFragment) {
            transaction.hide(voiceChatFragment);
        }
        /*if (null != voiceCommFragment) {
            transaction.hide(voiceCommFragment);
        }*/
        if (null != nearbyFragment) {
            transaction.hide(nearbyFragment);
        }
        if (null != meFragment) {
            transaction.hide(meFragment);
        }
    }
    @Override
    protected void showFragment(FragmentTransaction transaction, int index) {
        super.showFragment(transaction, index);
        switch (index) {
            case 0:
                showFragmentTag = "CommunityFragment";
                mainCommIv.setImageResource(R.mipmap.comm);
                mainCommTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (commFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    commFragment = new CommunityFragment();
                    transaction.add(R.id.frameLayout, commFragment, showFragmentTag);

                } else {
                    if (commFragment.isHidden()) {
                      // Logger.i(TAG, "gogoFragment.show()");
                        // 如果GogoFragment不为空，则直接将它显示出来
                        transaction.show(commFragment);
                    }
                }
                break;
            case 1:
                showFragmentTag = "VoiceChatFragment";
                mainVoiceChatIv.setImageResource(R.mipmap.chat);
                mainVoiceChatTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (voiceChatFragment == null) {
                    // MoneyBagMainNewFragment，则创建一个并添加到界面上
                    voiceChatFragment = new VoiceChatFragment();
                    transaction.add(R.id.frameLayout, voiceChatFragment, showFragmentTag);
                } else {
                    if (voiceChatFragment.isHidden()) {
                        // MoneyBagMainNewFragment，则直接将它显示出来
                        transaction.show(voiceChatFragment);
                    }
                }
                break;
            /*case 2:
                showFragmentTag = "VoiceCommFragment";
                //spIv.setImageResource(R.mipmap.shangcheng_xuanzhong_png);
                //spTv.setTextColor(getResources().getColor(R.color.colore60b49));
                if (voiceCommFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    voiceCommFragment = new VoiceCommFragment();
                    transaction.add(R.id.frameLayout, voiceCommFragment, showFragmentTag);
                } else {
                    if (voiceCommFragment.isHidden()) {
                        // 如果GogoFragment不为空，则直接将它显示出来
                        transaction.show(voiceCommFragment);
                    }
                }
                break;*/
            case 3:
                showFragmentTag = "NearbyFragment";
                mainNearbyIv.setImageResource(R.mipmap.nearby);
                mainNearbyTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (nearbyFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    nearbyFragment = new NearbyFragment();
                    transaction.add(R.id.frameLayout, nearbyFragment, showFragmentTag);
                } else {
                    if (nearbyFragment.isHidden()) {
                        // 如果GogoFragment不为空，则直接将它显示出来
                        transaction.show(nearbyFragment);
                    }
                }
                break;
            case 4:
                showFragmentTag = "MeFragment";
                mainMeIv.setImageResource(R.mipmap.me);
                mainMeTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (meFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    meFragment = new MeFragment();
                    transaction.add(R.id.frameLayout, meFragment, showFragmentTag);
                } else {
                    if (meFragment.isHidden()) {
                        // 如果GogoFragment不为空，则直接将它显示出来
                        transaction.show(meFragment);
                    }
                }
                break;
            default:
                break;
        }
    }


   /**
            * 定位权限判断
             * @param
     */
    public void showContacts() {
        // Verify that all required contact permissions have been granted.
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            requestContactsPermissions();
        } else {
            //Log.i(TAG,
                   // "Contact permissions have already been granted. Displaying contact details.");
            startLocation();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        } else {
            startLocation();
        }
        FileUtils.deleteAllFile(ConstantSet.VOICE);
        FileUtils.deleteAllFile(ConstantSet.VOICE+ConstantSet.VOICEINTR_PATH);
        FileUtils.deleteAllFile(ConstantSet.VOICEINTR+ConstantSet.VOICEINTR_PATH);
        //请求礼物
        showContactsGift();
        /*new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                BroadcastManager.getInstance(context).sendBroadcast("apk");
            }
        },1000);
        BroadcastManager.getInstance(context).addAction("apk", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(TAG, "onReceive: -----------");
                Utils.setIgnoreVersion(activity);
            }
        });*/
    }
    /**
     * @method
     * @description 判断升级
     * @date: 2018/11/6 18:03
     * @author: ljp
     * @return
     */
    private void showPopu(GiftDataBean.ObjectBean object,String flag) {
        View view = View.inflate(context,R.layout.popu_version_upgrade,null);
        LinearLayout linearVersion1 = view.findViewById(R.id.linear_version_1);
        LinearLayout linearVersion0 = view.findViewById(R.id.linear_version_0);
        if(flag.equals("1")){//必须升级
            linearVersion1.setVisibility(View.VISIBLE);
        }else {
            linearVersion0.setVisibility(View.VISIBLE);
        }
        TextView tvVerName =  view.findViewById(R.id.tv_verName);
        TextView tvVerContent =  view.findViewById(R.id.tv_version_text);
        TextView tvReject =  view.findViewById(R.id.tv_reject);
        TextView tvUpdate =  view.findViewById(R.id.tv_update);
        TextView tvUpdate1 =  view.findViewById(R.id.tv_update_1);//必须升级
        PopUtils.showPopupWindowUpdat(activity,view,false);
        String[] strings = Utils.spitPictureUrl(object.getSysVersion());
        tvVerName.setText("V"+strings[1]);
        tvVerContent.setText(object.getContent());
        tvReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShow = false;
                PopUtils.hidePopupWindow();
                /*PopUtils.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
                        params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        activity.getWindow().setAttributes(params);
                        PopUtils.getPopupWindow().dismiss();
                    }
                });*/
            }
        });
        tvUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isDownloadManagerAvailable(context)) {
                    isShow = false;
                    PopUtils.hidePopupWindow();
                    Intent serviceIntent = new Intent(MainActivity.this,DownloadService.class);
                    Log.i(TAG, "onClick: -----------"+OssConfig.OSS_HTTP+object.getDownloadUrl());
                    serviceIntent.setData(Uri.parse(OssConfig.OSS_HTTP+object.getDownloadUrl()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startForegroundService(serviceIntent);
                    } else {
                        startService(serviceIntent);
                    }


                } else {
                    toast_MakeText("下载管理器已被禁用，请启用之后下载隐隐语聊新版本！");
                }
            }
        });
        tvUpdate1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isDownloadManagerAvailable(context)) {
                    isShow = false;
                    toast_MakeText("更新下载中，请稍等……");
                    Intent serviceIntent = new Intent(MainActivity.this,DownloadService.class);
                    serviceIntent.setData(Uri.parse(OssConfig.OSS_HTTP+object.getDownloadUrl()));
                    startService(serviceIntent);
                } else {
                    toast_MakeText("下载管理器已被禁用，请启用之后下载隐隐语聊新版本！");
                }
            }
        });
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event){
        return super.dispatchTouchEvent(event);
    }
    @Override
    public void onBackPressed() {
        if( PopUtils.isPopShowing()){
            return ;
        }
        super.onBackPressed();
    }
    MyReceiver receiver = new MyReceiver();
    //绑定下载服务
    private void regist() {
        IntentFilter intentFilter = new IntentFilter(DownloadService.BROADCAST_ACTION);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    /*自动获取本地安装包, 进行更新*/
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            if(isShow) {
                //regist();
              //  setHttpVersion();
            }
        }
        super.onWindowFocusChanged(hasFocus);
    }

    /**
     * @method
     * @description 请求判断更新
     * @date: 2018/11/19 15:57
     * @author: ljp
     * @return
     */
    private void setHttpVersion() {
        String channel = Utils.getChannel(context);//版本号
        MeInfoService.uplodingVersion(mySeleInfo.getId(),token,deviceInfo,channel,"1").subscribe(giftDataBean -> {
            if(giftDataBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                //Log.i(TAG, "setHttpVersion: --------"+giftDataBean.getObject().toString());
                GiftDataBean.ObjectBean object = giftDataBean.getObject();
                String[] strings = Utils.spitPictureUrl(object.getSysVersion());
                int versionMin = Integer.parseInt(Utils.spitStringVersion(strings[0]));//最小版本号
                int versionMax = Integer.parseInt(Utils.spitStringVersion(strings[1]));//最大版本号
                String localVersionName = Utils.getLocalVersionName(activity);
                int present = Integer.parseInt(Utils.spitStringVersion(localVersionName));//当前版本版本号
               // Log.i(TAG, "setHttpVersion: ------present----"+present);
               // Log.i(TAG, "setHttpVersion: ------versionMax----"+versionMax);
                if(present < versionMin){//当前版本号是否小于最低版本号  必须升级
                    showPopu(object,"1");
                }else if(present < versionMax){//当前版本号是否小于最高版本号   正常升级  可取消
                    showPopu(object,"0");
                }
            }
        },throwable -> {
            Log.i(TAG, "uplodingGif: ---throwable--"+throwable.toString());
        });
    }
    /**
     * 权限判断
     * @param
     */
    public void showContactsGift() {
        // Verify that all required contact permissions have been granted.
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestContactsPermissions();
        } else {
            setHttpGif();
        }
    }
    /**
    * @method
    * @description 请求礼物列表
    * @date: 2018/11/19 15:57
    * @author: ljp
    * @return
    */
    private void setHttpGif() {
       // SPUtils.setEditorKeyValue(SPUtils.SP_GIF_VERSION, "1");
        String gifVersion = SPUtils.getEditoString(SPUtils.SP_GIF_VERSION);//礼物版本号
        MeInfoService.uplodingGif(mySeleInfo.getId(),token,deviceInfo).subscribe(giftDataBean -> {
            //Log.i(TAG, "setHttpGif: ------"+giftDataBean.toString());
            Log.i(TAG, "setHttpGif: ---gifVersion---"+gifVersion);
            if(giftDataBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                if(giftDataBean.getList() != null && giftDataBean.getList().size()!= 0) {
                    GiftDataBean<ListBean> response$T = Utils.getResponse$T(Utils.toJson(giftDataBean), ListBean.class);
                    List<ListBean> listBeans = response$T.getList();
                    for (int i = 0; i < listBeans.size(); i++) {
                        ListBean listBean = listBeans.get(i);
                       // Log.i(TAG, "setHttpGif: -----------"+listBean.toString());
                    }
                    if (!TextUtils.isEmpty(gifVersion)) {//版本号为空，本地没有礼物，保存礼物列表 下载礼物
                        if (!gifVersion.equals(giftDataBean.getVersion())) {//版本号不同，礼物更新，保存礼物列表 下载礼物
                          /*  //读取本地数据库，判断长度是否相同，然后比对礼物id
                            RealmResults<ListBean> results = RealmUtils.getInstance()
                                    .getRealm()
                                    .where(ListBean.class)
                                    .findAll();
                            //长度不等，重新写入数据库
                            if (results.size() != listBeans.size()) {*/
                                //删除所有数据，然后重新写入
                                clearRealm();
                                for (int i = 0; i < listBeans.size(); i++) {
                                    ListBean listBean = listBeans.get(i);
                                    //保存至数据库
                                    RealmUtils.getInstance().copyToRealmOrUpdate(listBean);
                                }
                                //下载礼物
                                uplodingGif(listBeans);
                                //保存礼物版本号
                                SPUtils.setEditorKeyValue(SPUtils.SP_GIF_VERSION, giftDataBean.getVersion());
                           /* } else {//比对本地数据库礼物列表和网络礼物列表
                                initRealmGif(results, listBeans, giftDataBean.getVersion());
                            }*/
                        }else {
                            RealmResults<ListBean> results = RealmUtils.getInstance()
                                    .getRealm()
                                    .where(ListBean.class)
                                    .findAll();
                           // Log.i(TAG, "setHttpGif: ----results----"+results);
                            if(results == null){
                                for (int i = 0; i < listBeans.size(); i++) {
                                    // Log.i(TAG, "setHttpGif: -----"+giftDataBean1.get(i).toString());
                                    ListBean listBean = listBeans.get(i);
                                    //保存至数据库
                                    RealmUtils.getInstance().copyToRealmOrUpdate(listBean);
                                }
                                //保存礼物版本号
                                SPUtils.setEditorKeyValue(SPUtils.SP_GIF_VERSION, giftDataBean.getVersion());
                                //下载礼物
                                uplodingGif(listBeans);
                            }
                        }
                    } else {//版本号为空，本地没有礼物，保存礼物列表 下载礼物
                        for (int i = 0; i < listBeans.size(); i++) {
                            // Log.i(TAG, "setHttpGif: -----"+giftDataBean1.get(i).toString());
                            ListBean listBean = listBeans.get(i);
                            //保存至数据库
                            RealmUtils.getInstance().copyToRealmOrUpdate(listBean);
                        }
                        //保存礼物版本号
                        SPUtils.setEditorKeyValue(SPUtils.SP_GIF_VERSION, giftDataBean.getVersion());
                        //下载礼物
                        uplodingGif(listBeans);
                    }
                }
            }
        },throwable -> {
            Log.i(TAG, "uplodingGif: ---throwable--"+throwable.toString());
        });
    }
    /**
    * @method
    * @description 删除所有数据
    * @date: 2018/11/26 14:27
    * @author: ljp
    * @return
    */
    private void clearRealm() {
        RealmResults<ListBean> results = RealmUtils.getInstance()
                .getRealm()
                .where(ListBean.class)
                .findAll();
        RealmUtils.getInstance().beginTransaction();
        //删除所有数据
        results.deleteAllFromRealm();
        RealmUtils.getInstance().commitTransaction();
    }
    /**
    * @method
    * @description 比对本地数据库礼物列表和网络礼物列表
    * @date: 2018/11/19 16:16
    * @author: ljp
    * @return
    */
    private void initRealmGif(RealmResults<ListBean> results, List<ListBean> gifLists, String version) {
        //读取本地数据库，判断长度是否相同，然后比对礼物id
        for (int i = 0;i< gifLists.size();i++){
            //Log.i(TAG, "initRealmGif: ---results---"+results.get(i).getId());
            //Log.i(TAG, "initRealmGif: --gifLists----"+gifLists.get(i).getId());
           // Log.i(TAG, "initRealmGif: ---bn---"+results.get(i).getId().equals(gifLists.get(i).getId()));
            if(!results.get(i).getId().equals(gifLists.get(i).getId())){
                //礼物id 不相等，删除数据库中，然后插入新的数据
                RealmUtils.getInstance().deleteToRealm(i);
                ListBean listBean = gifLists.get(i);
                RealmUtils.getInstance().copyToRealmOrUpdate(listBean);
            }else {
               // Log.i(TAG, "initRealmGif: ----else---"+gifLists.get(i).getId());
            }
        }
        //下载礼物
        uplodingGif(gifLists);
        //保存礼物版本号
        SPUtils.setEditorKeyValue(SPUtils.SP_GIF_VERSION,version);
    }

    /**
    * @method
    * @description 下载礼物
    * @date: 2018/11/19 16:12
    * @author: ljp
    * @return
    */
    private void uplodingGif(List<ListBean> gifLists){
        //读取本地数据库，判断长度是否相同，然后比对礼物id
       /* RealmResults<ListBean> results = RealmUtils.getInstance()
                .getRealm()
                .where(ListBean.class)
                .findAll();*/
        //Log.i(TAG, "uplodingGif: ------"+results.size());
        setThreadGift(gifLists);
       // setThreadGiftAnimation(gifLists);
    }
    /**
     * @method
     * @description 启动线程池下载静态礼物地址
     * @date: 2018/11/15 15:14
     * @author: ljp
     * @return
     */
    private void setThreadGift(List<ListBean> gifLists) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < gifLists.size(); i++) {
                    if(!TextUtils.isEmpty(gifLists.get(i).getImgUrl())) {
                        String voiceInfo = gifLists.get(i).getImgUrl();
                        int finalI = i;
                        OssClient.getInstance().init(context).fileDownload(voiceInfo, new OssClient.OnDownloadFile() {
                            @Override
                            public void onDownFileSuccess(InputStream inputStream) {
                                String voiceName = Utils.getVoiceName(gifLists.get(finalI).getImgUrl());
                                //Log.i(TAG, "onDownFileSuccess: ------" + ConstantSet.VOICEINTR + ConstantSet.GIF_PATH + voiceName);
                                String path = ConstantSet.VOICEINTR;
                                try {
                                    OssConfig.writeToLocalGif(path, inputStream, voiceName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onDownFileProgress(String progress) {
                            }
                        });
                    }
                }
            }
        });
    }
    /**
     * @method
     * @description 启动线程池下载动态礼物地址
     * @date: 2018/11/15 15:14
     * @author: ljp
     * @return
     */
    private void setThreadGiftAnimation(List<ListBean> gifLists) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < gifLists.size(); i++) {
                    if(!TextUtils.isEmpty(gifLists.get(i).getAnimationUrl())){
                        String gifAnimatoionUrl = gifLists.get(i).getAnimationUrl();
                        int finalI = i;
                        OssClient.getInstance().init(context).fileDownload(gifAnimatoionUrl, new OssClient.OnDownloadFile() {
                            @Override
                            public void onDownFileSuccess(InputStream inputStream) {
                               // Log.i(TAG, "run: -----"+ConstantSet.VOICEINTR + ConstantSet.GIF_PATH+ Utils.getVoiceName(gifAnimatoionUrl));
                                String path = ConstantSet.VOICEINTR;
                                try {
                                    OssConfig.writeToLocalGif(path, inputStream, gifAnimatoionUrl);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            @Override
                            public void onDownFileProgress(String progress) {
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * 权限判断
     */
    private void requestContactsPermissions() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                || ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)
                ) {
           // Log.i(TAG, "requestContactsPermissions: -----" + "--------------");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("隐隐申请读取位置权限");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat
                            .requestPermissions(MainActivity.this, PERMISSIONS_CONTACT,
                                    REQUEST_CONTACTS);
                    dialog.dismiss();//此处换成删除，这是一个结束返回
                }
            });
            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.create().show();
        } else {
            ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        }
    }
    /**
            * 启动定位
     */
    private void startLocation() {
        locationService = App.getInstance().locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }
    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();
                if (longitude != 0 && latitude != 0) {
                    App.getInstance().setStop();
                    //App.getInstance().locationService = null;
                    setGPS(longitude, latitude);
                   /* if (SPUtils.getEditoString("longitude").equals("") || SPUtils.getEditoString("longitude") == null) {
                        SPUtils.setEditorKeyValue("longitude", longitude + "");
                        SPUtils.setEditorKeyValue("latitude", latitude + "");
                        if (!String.valueOf(longitude).contains("E") || !String.valueOf(latitude).contains("E")) {
                            setGPS(longitude, latitude);
                        }
                    } else if (Double.parseDouble(SPUtils.getEditoString("longitude")) != longitude && Double.parseDouble(SPUtils.getEditoString("latitude")) != latitude) {
                        SPUtils.setEditorKeyValue("longitude", longitude + "");
                        SPUtils.setEditorKeyValue("latitude", latitude + "");
                        if (!String.valueOf(longitude).contains("E") || !String.valueOf(latitude).contains("E")) {
                            setGPS(longitude, latitude);
                        }*/
                   // }
                }
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                Log.i(TAG, "onReceiveLocation: -----" + BDLocation.TypeServerError);
            }
        }

        public void onConnectHotSpotMessage(String s, int i) {
            Log.i(TAG, "onConnectHotSpotMessage: ------" + s);

        }
    };
    /**
    * @method
    * @description 请求服务器提交经纬度
    * @date: 2018/11/5 10:10
    * @author: ljp
    * @return
    */
    private void setGPS(double longitude, double latitude) {
        Log.i(TAG, "setGPS: ---longitude---"+longitude+"--latitude--"+latitude);
        MeInfoService.updateLongitude(mySeleInfo.getId(),token,deviceInfo,Utils.spitLongString(String.valueOf(longitude)),
                Utils.spitLongString(String.valueOf(latitude))).subscribe(result -> {
                    if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                        locationService.stop();
                        App.getInstance().locationService.stop();
                        SPUtils.setEditorKeyValue("longitude", Utils.spitLongString(String.valueOf(longitude)));
                        SPUtils.setEditorKeyValue("dimension", Utils.spitLongString(String.valueOf(latitude)));
                    }
            Log.i(TAG, "setGPS: -----"+result.toString());
        },throwable -> {
            Log.i(TAG, "setGPS: ---------"+throwable.toString());

        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (PopUtils.isPopShowing()) {
                PopUtils.hidePopupWindow();
                return true;
            }
            exit();
         /*   Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);*/
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private long nowTime = 0;
    /**
     * 退出程序
     */
    private void exit() {
        if (PopUtils.isPopShowing()) {
            PopUtils.hidePopupWindow();
        } else if (System.currentTimeMillis() - nowTime < 2000) {
            // RongIM.getInstance().disconnect();
            removeAllActivity();
            System.exit(0);
        } else {
            toast_MakeText("再按一次退出程序");
            nowTime = System.currentTimeMillis();
        }
    }
    private List<Conversation> conversationList = new LinkedList<>();
    @Override
    protected void onPause() {
        super.onPause();
    }
    /**
     * 初始化界面或刷新界面
     *
     * @param conversationList
     */
    @Override
    public void initView(List<TIMConversation> conversationList) {
        this.conversationList.clear();
        for (TIMConversation item : conversationList) {
            switch (item.getType()) {
                case C2C:
                    this.conversationList.add(new NomalConversation(item));
                case Group:
                    break;
            }
        }
    }

    /**
     * 更新最新消息显示
     *
     * @param message 最后一条消息
     */
    @Override
    public void updateMessage(TIMMessage message) {
        if (message == null) {
            return;
        }
        if (message.getConversation().getType() == TIMConversationType.System) {
            //groupManagerPresenter.getGroupManageLastMessage();
            return;
        }
        //if (MessageFactory.getMessage(message) instanceof CustomMessage) return;
        NomalConversation conversation = new NomalConversation(message.getConversation());
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation c = iterator.next();
            if (conversation.equals(c)) {
                conversation = (NomalConversation) c;
                iterator.remove();
                break;
            }
        }
        //presenter.delConversation(conversation.getType(), conversation.getIdentify());
        conversation.setLastMessage(MessageFactory.getMessage(message));
        conversationList.add(conversation);
        Collections.sort(conversationList);
        refresh();
    }

    @Override
    public void removeConversation(String identify) {

    }

    /**
     * 刷新
     */
    @Override
    public void refresh() {
        Collections.sort(conversationList);
        if(commFragment != null){
            commFragment.setMsgUnread(getTotalUnreadNum() == 0);
        }
    }
    /**
     * @return
     * @method
     * @description 获取未读消息数量
     * @date: 2018/12/17 10:43
     * @author: ljp
     */
    private long getTotalUnreadNum() {
        long num = 0;
        for (Conversation conversation : conversationList) {
            num += conversation.getUnreadNum();
        }
        return num;
    }

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Utils. setIgnoreVersion(activity);
           /* String data = intent.getStringExtra(DownloadService.EXTENDED_DATA_STATUS);
            //Log.i("test", data);
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            Toast.makeText(MainActivity.this, "隐隐语聊新版本下载完成！", Toast.LENGTH_SHORT).show();
            intent = new Intent(Intent.ACTION_VIEW);
            //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            File apkFile = Utils.queryDownloadedApk(context);
            if(Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri =
                        FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".android7.fileprovider", apkFile);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            }else{
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }
            //intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myApp.apk")),
             //       "application/vnd.android.package-archive");
            startActivity(intent);*/

        }
    }
}
